/**
 * 2020-05-08 修改bean属性类型错误 jinchengzhen
 */
package org.simple.jdbc.resolver;

import org.simple.jdbc.table.annotation.PrimaryKey;
import org.simple.jdbc.table.annotation.Table;
import org.simple.jdbc.table.bean.ColumnBean;
import org.simple.jdbc.table.bean.TableBean;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author jinchengzhen
 */
public class TableResolver implements Resolver<TableBean> {
    private Class<?> tableClazz;

    public TableResolver(Class<?> tableClazz) {
        if (tableClazz.isInterface()) {
            this.tableClazz = tableClazz;
        }
    }

    @Override
    public TableBean resolver() {
        Objects.requireNonNull(tableClazz, "table class is null because it is not interface!");
        Table table = tableClazz.getAnnotation(Table.class);
        Class<?> beanClass = table.beanClass();
        TableBean tableBean = new TableBean();
        List<ColumnBean> columnBeanList = new ArrayList<>();
        Field[] fields = tableClazz.getFields();
        for (Field field : fields) {
            field.setAccessible(true);
            ColumnBean columnBean = getColumnBean(field, tableClazz, beanClass);
            if (field.getAnnotation(PrimaryKey.class) != null) {
                tableBean.setPrimaryColumn(columnBean);
            }
            columnBeanList.add(columnBean);
        }
        tableBean.setBeanClass(table.beanClass());
        tableBean.setTableName(table.name());
        tableBean.setColumnBeanList(columnBeanList);
        return tableBean;
    }

    public ColumnBean getColumnBean(Field field, Class<?> tableClazz, Class<?> beanClazz) {
        ColumnBean columnBean = new ColumnBean();
        try {
            Class<?> beanPropertyType = beanClazz.getDeclaredField(field.getName()).getType();
            columnBean.setBeanPropertyType(beanPropertyType);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        columnBean.setPropertyName(field.getName());
        try {
            columnBean.setColumnName((String) field.get(tableClazz));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return columnBean;
    }
}
